
#version 330 core

struct Material {
sampler2D diffuse;
sampler2D specular;
float     shininess;
};

struct Light {
//决定是位置光还是定向光
vec4 lightVector;

//灯的属性
vec3 ambient;
vec3 diffuse;
vec3 specular;

//衰减常量
float constant;
float linear;
float quadratic;

//聚光灯属性
vec3  position;
vec3  direction;
float cutOff;
float outerCutOff;
};

out vec4 FragColor;

in vec3 Normal;
in vec3 FragPos;
in vec2 TexCoords;

uniform vec3 viewPos;

uniform Material material;
uniform Light light;

//聚光灯,手电筒
void main()
{
vec3 lightDir;

if(light.lightVector.w == 0.0)     //位置光
lightDir = normalize(vec3(light.lightVector) - FragPos);
else if(light.lightVector.w == 1.0)// 定向光
lightDir = normalize(-vec3(light.lightVector));

// 环境光
vec3 ambient  = light.ambient  * vec3(texture(material.diffuse, TexCoords));

// 漫反射
vec3 norm = normalize(Normal);// 执行定向光照计算
float diff = max(dot(norm, lightDir), 0.0);
vec3 diffuse  = light.diffuse  * diff * vec3(texture(material.diffuse, TexCoords));

// 镜面光
vec3 viewDir = normalize(viewPos - FragPos);
vec3 reflectDir = reflect(-lightDir, norm);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords));

// spotlight (soft edges)
float theta = dot(lightDir, normalize(-light.direction));
float epsilon = (light.cutOff - light.outerCutOff);
float intensity = clamp((theta - light.outerCutOff) / epsilon, 0.0, 1.0);//把第一个参数约束(Clamp)在了0.0到1.0之间。这保证强度值不会在[0, 1]区间之外(小于0为0,大于1为1)
diffuse  *= intensity;
specular *= intensity;

float distance    = length(vec3(light.lightVector) - FragPos);
float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance));

ambient  *= attenuation;
diffuse  *= attenuation;
specular *= attenuation;

vec3 result = ambient + diffuse + specular;
FragColor = vec4(ambient + diffuse + specular, 1.0);


}

